package com.smsc.headend.task.engine.executor.impl.deviceconfig;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.map.MapUtil;
import com.smsc.headend.common.enums.PaymentSwithPreToPostOptGroupEnum;
import com.smsc.headend.common.enums.errorcode.TaskExecuteErrorCode;
import com.smsc.headend.common.utils.RedisKeys;
import com.smsc.headend.common.utils.RedisUtils;
import com.smsc.headend.module.asset.dmo.ComConfigDMO;
import com.smsc.headend.module.asset.dmo.MeterConfigDMO;
import com.smsc.headend.module.asset.entity.ComEntity;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.common.entity.DeviceOperation;
import com.smsc.headend.module.data.dmo.DeviceSAPandKeys;
import com.smsc.headend.module.data.dto.DataItemDTO;
import com.smsc.headend.module.data.enums.DictionaryType;
import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.AtomicTaskState;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.task.enums.SubTaskStatus;
import com.smsc.headend.module.task.enums.TaskType;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskExecutorException;
import com.smsc.headend.task.engine.executor.TaskExecutor;
import com.smsc.headend.task.engine.facade.DataItemFacade;
import com.smsc.headend.task.engine.handler.impl.deviceconfig.FrozenLoadProfileHandler;
import com.smsc.headend.task.engine.service.ConnectorService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.task.TaskPacketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * (业务实现)
 *
 * @author wjh
 * @date 2022/5/25 10:06.
 */
@Slf4j
public class SetProfileCaptureExecutor implements TaskExecutor {

    @Autowired
    TaskPacketService packetService;
    @Autowired
    ConnectorService connectorService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    FeignAssetManagementService assetManagementRemoteService;
    @Autowired
    DataItemFacade dataItemFacade;
    @Autowired
    TaskDAO taskDAO;
    @Autowired
    AssetService assetService;
    @Autowired
    FeignAssetManagementService assetManagementService;

    @Override
    public AtomicTaskState execute(Task task, AtomicTask atomicTask) throws UDISTaskExecutorException {
        DeviceOperation dictionary = assetService.getDictionary(atomicTask.getOperationId(), DictionaryType.Operation.getType());
        Meter meter = getMeter(task, assetService);
        if (task.getMeterId() != null && meter == null) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.METER_NOT_EXISTS.toString());
        }
        ComEntity terminal = assetService.getComById(task.getComId());
        ComConfigDMO comConfigDMO = assetService.getComConfigById(task.getComId());
        String interfaceType = comConfigDMO.getInterfaceType();
        Boolean isShortName = comConfigDMO.getIsShortName();
        MeterConfigDMO meterConfigDMO = null;
        if (task.getMeterId() != null) {
            meterConfigDMO = assetService.getMeterConfigById(task.getMeterId());
            interfaceType = meterConfigDMO.getInterfaceType();
            isShortName = meterConfigDMO.getIsShortName();
        }
        List<DataItemDTO> dataItemDTOList = dataItemFacade.getDataItemsByOperation(meter, terminal, dictionary, getParameterMap(task, atomicTask), comConfigDMO.getModelId());
        if (CollectionUtils.isEmpty(dataItemDTOList)) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.DATAITEM_NOT_EXISTS.toString());
        }
        DeviceSAPandKeys deviceKeys = meter != null ? assetManagementRemoteService.getMeterCommunicationKey(meter.getMeterId(), dataItemDTOList.get(0).getRoleId()) :
                assetManagementRemoteService.getTerminalCommunicationKey(terminal.getComId(), dataItemDTOList.get(0).getRoleId());
        byte[] packets = packetService.profileCaptureAction(dataItemDTOList.get(0), interfaceType, 0, isShortName, deviceKeys);
        if (packets == null) {
            throw new UDISTaskExecutorException(TaskExecuteErrorCode.PACKETS_IS_NULL.toString());
        }
        log.info(ByteUtils.byteToHexString(packets));
        connectorService.sendPacket(task, atomicTask, dataItemDTOList.get(0).getRoleId(), task.getIsODR(), packets);

        if (TaskType.SwitchMeterPaymentPreToPost.toString().equalsIgnoreCase(task.getTaskType())) {
            Long captureTime = System.currentTimeMillis();
            String  captureTimeKey = RedisKeys.getPaymentSwitchProfileCaptureTime(task.getTaskNo());
            redisUtils.set(captureTimeKey,captureTime,5 * 60 * 60L);
            Map<String, Object> parameterMap = getParameterMap(task, atomicTask);
            Long taskId = MapUtil.getLong(parameterMap, "taskId");
            assetManagementService.updateStepStatusToPost(taskId,task.getTaskNo(), task.getMeterId(), PaymentSwithPreToPostOptGroupEnum.FROZEN_DAILY_BILLING_PROFILE.getOperationGroup().longValue(), SubTaskStatus.Processing.getCode(), SystemClock.now() / 1000, null,
                    null, false);
        }
        Class handlerClass = getHandlerClass(atomicTask);
        return createAtomicState(handlerClass);
    }

    @Override
    public Boolean handleFailure(Task task, AtomicTask atomicTask, String message) {
        if (TaskType.SwitchMeterPaymentPreToPost.toString().equalsIgnoreCase(task.getTaskType())) {
            Map<String, Object> parameterMap = getParameterMap(task, atomicTask);
            Long taskId = MapUtil.getLong(parameterMap, "taskId");
            assetManagementService.updateStepStatusToPost(taskId,task.getTaskNo(), task.getMeterId(), PaymentSwithPreToPostOptGroupEnum.FROZEN_DAILY_BILLING_PROFILE.getOperationGroup().longValue(), SubTaskStatus.Failed.getCode(), SystemClock.now() / 1000, SystemClock.now() / 1000,
                    String.format("handle %s fail, [%s]", OperationName.forId(atomicTask.getOperationId()).getName(), message), false);
        }
        return true;
    }

    private Class getHandlerClass(AtomicTask atomicTask) throws UDISTaskExecutorException {
        Class cla = null;
        switch (OperationGroup.forId(atomicTask.getGroupId().intValue())) {
            case FrozenMonthlyBillingProfile:
                cla = FrozenLoadProfileHandler.class;
                break;
            default:
                throw new UDISTaskExecutorException(TaskExecuteErrorCode.UNEXPECTED_VALUE.toString() + atomicTask.getGroupId().intValue());
        }
        return cla;
    }
}
